package geektime.nio.smtp;
/**
 *
 **/

import io.netty.util.internal.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author weiwei
 * @Date 2022-01-13 09:07
 * @description
 **/
public class SMTProcess {

    public static Map<String,SMTProcess> processMap = new HashMap<>();


    private String lastCorrectRead;

    private final List<String> nextBack = new ArrayList<>();

    private boolean firstReadDone = false;

    private String data;


    public String backMsg(String read){
        //根据read判断当前所处进程
        if(StringUtil.isNullOrEmpty(read)){
            return "500 empty";
        }
        if(!nextBack.contains(read)){
            return "503 sequence error";
        }

        lastCorrectRead = read;

        return "";
    }

    private String handleRead(String read){
        if(read.equals("HELO")){
            firstReadDone = true;
            return "250 OK";
        }
        if(read.startsWith("MAIL FROM:")){
            return "250 …";
        }
        if(read.startsWith("RCPT TO:")){
            return "250 …";
        }
        if(read.equals("DATA")){
            return "354 Enter mail, end with \".\" on a line by itself";
        }
        if(read.equals(".")){
            return "250 Message sent";
        }
        if(read.equals("QUIT")){
            return "221 Bye";
        }
        if(isWriteData()){
            return "";
        }
        return "500 fail to identify ";
    }

    private boolean isWriteData(){
        return lastCorrectRead.equals("DATA");
    }

    private boolean sortCheck(String read){
        if(!firstReadDone && read.equals("HELO")){
            return true;
        }
        if(firstReadDone){
            if(lastCorrectRead.startsWith("HELO") && read.startsWith("MAIL FROM:")){
                return true;
            }
            if(lastCorrectRead.startsWith("MAIL FROM:") && read.startsWith("RCPT TO:")){
                return true;
            }
            if(lastCorrectRead.startsWith("RCPT TO:") && read.equals("DATA")){
                return true;
            }
            if(lastCorrectRead.equals("DATA")){
                return true;
            }
            return lastCorrectRead.equals(".") && read.equals("QUIT");
        }
        return false;
    }
}
